package com.atguigu.r2dbc.service.impl;

import com.atguigu.r2dbc.entity.StudentDO;
import com.atguigu.r2dbc.repositories.StudentRepository;
import com.atguigu.r2dbc.service.StudentService;

import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;


@Service
public class StudentServiceImpl implements StudentService {
    private final StudentRepository studentRepository;

    public StudentServiceImpl(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    @Override
    public Flux<StudentDO> findAll() {
        return studentRepository.findAll();
    }

    @Override
    public Mono<StudentDO> findById(Long id) {
        return studentRepository.findById(id);
    }

    @Override
    public Flux<StudentDO> findByName(String name) {
        return studentRepository.findByName(name);
    }

    @Override
    public Mono<StudentDO> save(StudentDO student) {
        return studentRepository.save(student).handle((item, sink) -> {
            if (item.getName().contains("大")) {
                sink.error(new IllegalArgumentException("名称非法"));
            } else {
                sink.next(item);
            }
        });
    }

    @Override
    public Mono<StudentDO> update(StudentDO student) {
        return studentRepository.save(student).handle((item, sink) -> {
            if (item.getName().contains("大")) {
                sink.error(new IllegalArgumentException("名称非法"));
            } else {
                sink.next(item);
            }
        });
    }

    @Override
    public Mono<Boolean> deleteByName(String name) {
        return studentRepository.deleteByName(name);
    }

    @Override
    public Mono<Void> deleteById(Long id) {
        return studentRepository.deleteById(id);
    }
}
